package com.yonyou.gmmc.service.wechatpush.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.dto.wechat.WcArticlesParamDto;
import org.marketing.common.dto.wechat.WcArticlesResultDto;
import org.marketing.common.dto.wechat.WcArticlesParamDto.Article;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.service.rest.RestServiceResultDto;
import org.marketing.common.service.rest.RestServiceUtil;
import org.marketing.common.service.wechat.WechatSendUtil;
import org.marketing.common.util.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yonyou.gmmc.service.wechatpush.dao.TmSmartReplyMapper;
import com.yonyou.gmmc.service.wechatpush.dao.TtUserProblemMapper;
import com.yonyou.gmmc.service.wechatpush.dto.AlterReplyDto;
import com.yonyou.gmmc.service.wechatpush.dto.NewsActivityDto;
import com.yonyou.gmmc.service.wechatpush.dto.WechatKeyWordDto;
import com.yonyou.gmmc.service.wechatpush.dto.WechatSmartReplyDto;
import com.yonyou.gmmc.service.wechatpush.entity.TmCarKnowledges;
import com.yonyou.gmmc.service.wechatpush.model.TtUserProblem;
import com.yonyou.gmmc.service.wechatpush.util.HttpUtil;
import com.yonyou.gmmc.service.wechatpush.util.HttpsUtil;

import net.sf.json.JSONObject;

@Transactional
@Service
public class WechatSmartReplyService {

    private static final Logger logger = Logger.getLogger(WechatSmartReplyService.class);
    @Autowired
    private TmSmartReplyMapper  tmSmartReplyMapper;
    @Autowired
    private TokenService        tokenService;
    @Autowired
    private TtUserProblemMapper ttUserProblemMapper;

    @Transactional(rollbackFor = ServiceBizException.class)
    public Map<String, Object> ifExistRule(String ruleName) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            List<WechatSmartReplyDto> list = tmSmartReplyMapper.queryRule(ruleName);
            if (list.size() > 0) {
                result.put("queryCode", "1");
                result.put("queryMsg", "规则名已存在");
            } else {
                result.put("queryCode", "0");
                result.put("queryMsg", "规则名可以使用");
            }
            result.put("errorCode", "0");
            result.put("errorMsg", "查询成功！");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.put("errorCode", "1");
            result.put("errorMsg", "查询异常！");
        }
        return result;
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public Map<String, Object> insertSmartReply(List<WechatSmartReplyDto> replyDto, List<WechatKeyWordDto> keywordDto) {
        Map<String, Object> result = new HashMap<String, Object>();
        Integer menuRootId = null;
        WechatSmartReplyDto wechatSmartReplyDto = new WechatSmartReplyDto();
        try {
            if (replyDto.get(0).getReplyType() == 3) {
                wechatSmartReplyDto.setReplyContent(keywordDto.get(0).getRuleName()/* +"根节点" */);
                wechatSmartReplyDto.setReplyType(3);
                wechatSmartReplyDto.setStatus(0);
            }
            if (replyDto.size() > 1 || replyDto.get(0).getReplyType() == 3) {
                logger.info("开始list的大小" + replyDto.size());
                logger.info("结束list的大小" + replyDto.size());
                Integer id = tmSmartReplyMapper.selectReplyId();
                wechatSmartReplyDto.setId(id);
                tmSmartReplyMapper.insertSingleReply(wechatSmartReplyDto);
                menuRootId = wechatSmartReplyDto.getReplyId();
                tmSmartReplyMapper.insertKeyword(keywordDto);
                tmSmartReplyMapper.insertSubmenuReply(replyDto);
            } else if (replyDto.size() == 1) {
                if (replyDto.get(0).getReplyType() == 2) {
                    String replyContent = getPicTextMediaId(replyDto.get(0).getGraphicId(),
                                                            replyDto.get(0).getGraphicType());
                    if (null != replyContent && "" != replyContent) {
                        replyDto.get(0).setReplyContent(replyContent);
                    } else {
                        result.put("errorWeChat", "1");
                        result.put("errorWeChatMsg", "微信上传图文失败");
                        throw new ServiceBizException("微信上传图文失败");
                    }
                }
                Integer id = tmSmartReplyMapper.selectReplyId();
                replyDto.get(0).setId(id);
                replyDto.get(0).setSubmenuParentId(id);
                tmSmartReplyMapper.insertSingleReply(replyDto.get(0));
                tmSmartReplyMapper.insertKeyword(keywordDto);
            } else {
                result.put("errorCode", "1");
                result.put("errorMsg", "不允许为空");
                return result;
            }
            result.put("errorCode", "0");
            result.put("errorMsg", "插入成功");
            result.put("menuRootId", menuRootId);
            logger.info("返回结果为：" + result);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.put("errorCode", "1");
            result.put("errorMsg", "插入失败");
        }
        return result;
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public PageInfo<WechatSmartReplyDto> getReplyRule(Map<String, Object> paramMap) throws ServiceBizException,
                                                                                    ServiceBizException {
        Map<String, Object> retMap = new HashMap<String, Object>();
        try {
            Page<WechatSmartReplyDto> pd = PageHelper.startPage(Integer.parseInt(paramMap.get("pageNum").toString()),
                                                                Integer.parseInt(paramMap.get("pageSize").toString()));
            List<WechatSmartReplyDto> dtoList = tmSmartReplyMapper.getReplyRule(paramMap);
            PageInfo<WechatSmartReplyDto> page = new PageInfo<WechatSmartReplyDto>(dtoList);
            if (dtoList.size() == 0) {
                retMap.put("flag", 0);
                retMap.put("msg", "查询不到数据");
            }
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public Map<String, Object> getMenuReplyDetail(Integer rootId) throws ServiceBizException, ServiceBizException {
        Map<String, Object> retMap = new HashMap<>();
        try {
            List<Map<String, Object>> retsult = new ArrayList<>();
            Map<String, Object> rootMap = new HashMap<>();
            WechatSmartReplyDto rootReply = tmSmartReplyMapper.queryReplyById(rootId);
            if (rootReply.getReplyType() == 2) {
                logger.info("图文类型为：" + rootReply.getGraphicType());
                if (rootReply.getGraphicType() == 3) {
                    logger.info("查询用车知识");
                    rootReply.setGraphicTitle(tmSmartReplyMapper.queryCarKnowledgeById(rootReply.getGraphicId()).getTitle());
                } else {
                    logger.info("查询咨询活动");
                    rootReply.setGraphicTitle(tmSmartReplyMapper.queryInforById(rootReply.getGraphicId()).getTitle());
                }
            }
            rootMap.put("replyObj", rootReply);
            rootMap.put("id", rootReply.getReplyId());
            rootMap.put("child", menuTraverse(rootId));
            retsult.add(rootMap);
            List<WechatKeyWordDto> keyWordList = tmSmartReplyMapper.queryKeyword(rootId);
            retMap.put("flag", 0);
            retMap.put("resultData", retsult);
            retMap.put("keyWord", keyWordList);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return retMap;
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public Map<String, Object> queryReply(Integer replyId) throws ServiceBizException, ServiceBizException {
        Map<String, Object> retMap = new HashMap<>();
        try {
            List<WechatSmartReplyDto> retsult = tmSmartReplyMapper.queryReply(replyId);
            String title = null;
            if (retsult.get(0).getReplyType() == 2) {
                for (WechatSmartReplyDto reply : retsult) {
                    String graphicContent = "";
                    if (reply.getGraphicType() == 3) {
                        String graphicContentUrl = tmSmartReplyMapper.queryCarKnowledgeById(reply.getGraphicId()).getContentUrl();
                        graphicContent = HttpUtil.sendGet(graphicContentUrl, "");
                        title = tmSmartReplyMapper.queryCarKnowledgeById(reply.getGraphicId()).getTitle();
                    } else {
                        String graphicContentUrl = tmSmartReplyMapper.queryInforById(reply.getGraphicId()).getContentPath();
                        graphicContent = HttpUtil.sendGet(graphicContentUrl, "");
                        title = tmSmartReplyMapper.queryInforById(reply.getGraphicId()).getTitle();
                    }
                    reply.setReplyContent(graphicContent);
                }
            }
            retMap.put("flag", 0);
            retMap.put("resultData", retsult);
            if (null != title) {
                retMap.put("title", title);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
        return retMap;
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public List<Map<String, Object>> menuTraverse(Integer rootId) {
        List<Map<String, Object>> retList = new ArrayList<>();
        List<WechatSmartReplyDto> temp = tmSmartReplyMapper.getNextMenuDetail(rootId);
        if (temp.size() > 0) {
            for (int i = 0; i < temp.size(); i++) {
                Map<String, Object> retMap = new HashMap<>();
                if (temp.get(i).getReplyType() == 2) {
                    logger.info("查询图文回复");
                    if (temp.get(i).getGraphicType() == 3) {
                        logger.info("回复为用车知识");
                        temp.get(i).setGraphicTitle(tmSmartReplyMapper.queryCarKnowledgeById(temp.get(i).getGraphicId()).getTitle());
                    } else {
                        logger.info("回复为资讯活动");
                        temp.get(i).setGraphicTitle(tmSmartReplyMapper.queryInforById(temp.get(i).getGraphicId()).getTitle());
                    }
                }
                retMap.put("replyObj", temp.get(i));
                retMap.put("id", temp.get(i).getReplyId());
                if (tmSmartReplyMapper.getNextMenuDetail(rootId).size() > 0) {
                    retMap.put("child", menuTraverse(temp.get(i).getReplyId()));
                }
                retList.add(retMap);
            }
        }
        return retList;
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public Map<String, Object> updateStatus(Integer rootId, Integer status) throws Exception {
        Map<String, Object> retMap = new HashMap<>();
        try {
            tmSmartReplyMapper.updateStatus(rootId, status);
            retMap.put("errorCode", 0);
            retMap.put("errMsg", "更新成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            retMap.put("errorCode", 1);
            retMap.put("errMsg", "更新失败");
        }
        return retMap;
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public PageInfo<NewsActivityDto> queryInforOrActity(Integer type,
                                                        Map<String, Object> paramMap) throws ServiceBizException,
                                                                                      ServiceBizException {
        Map<String, Object> retMap = new HashMap<>();
        try {
            Page<NewsActivityDto> pd = PageHelper.startPage(Integer.parseInt(paramMap.get("pageNum").toString()),
                                                            Integer.parseInt(paramMap.get("pageSize").toString()));

            List<NewsActivityDto> retsult;
            if (type == 0) {
                retsult = tmSmartReplyMapper.queryInfor(paramMap);
            } else {
                retsult = tmSmartReplyMapper.queryActivity(paramMap);
            }
            PageInfo<NewsActivityDto> page = new PageInfo<NewsActivityDto>(retsult);

            retMap.put("flag", 0);
            retMap.put("resultData", retsult);
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public String getPicTextMediaId(Integer graphicId, Integer graphicType) throws Exception {
        String picTextMediaid = "";
        String fileUrl = "";
        String title = "";
        String contentSourceUrl = "";
        String mediaId = getImgMediaId(graphicId, graphicType);
        if (null == mediaId || "" == mediaId) {
            return null;
        }
        try {
            if (graphicType == 3) {
                TmCarKnowledges ck = tmSmartReplyMapper.queryCarKnowledgeById(graphicId);
                if (ck != null) {
                    fileUrl = ck.getContentUrl();
                    title = ck.getTitle();
                    contentSourceUrl = fileUrl;
                } else {
                    throw new ServiceBizException("查询不到该用车知识");
                }
            } else {
                NewsActivityDto news = tmSmartReplyMapper.queryInforById(graphicId);
                if (news.getContentPath() != null) {
                    fileUrl = news.getContentPath();
                } else {
                    fileUrl = null;
                }
                title = news.getTitle();
                contentSourceUrl = fileUrl;
            }
            String content = "";
            if (fileUrl != null) {
                content = HttpUtil.sendGet(fileUrl, "");
            } else {
                content = title;
            }

            String accessToken = tokenService.genAccessToken();
            String url = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=" + accessToken;

            WcArticlesParamDto articleParamDto = new WcArticlesParamDto();
            List<Article> articleList = new ArrayList<>();
            articleParamDto.setArticles(articleList);
            Article articleDto = articleParamDto.generateArticle();
            articleDto.setAuthor("广汽三菱");
            articleDto.setContent(content);
            String digest = ""; // 文章简要说明
            articleDto.setDigest(digest);
            articleDto.setShowCoverPic(1);
            articleDto.setThumbMediaId(mediaId);
            articleDto.setTitle(title);
            articleDto.setContentSourceUrl("");
            articleList.add(articleDto);

            String jsonBody = RestServiceUtil.objectToJson(articleParamDto);
            logger.info("群发数据 =" + jsonBody);
            RestServiceResultDto resultDto = WechatSendUtil.postMessageForWechat(url, jsonBody);
            if (resultDto != null) {
                String resultBody = resultDto.getResultBody();
                logger.info("群发返回结果 response=" + resultBody);
                if (resultBody.contains("errcode") && resultBody.contains("errmsg")) {
                    logger.info("postPicTextInfo error:" + resultBody);
                }
                WcArticlesResultDto articleResDto = (WcArticlesResultDto) RestServiceUtil.jsonToObj(resultBody,
                                                                                                    WcArticlesResultDto.class);
                picTextMediaid = articleResDto.getMediaId();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return picTextMediaid;
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public String getImgMediaId(Integer graphicId, Integer graphicType) {
        logger.info("入参为：" + graphicId + "&&" + graphicType);
        String fileUrl = "";
        String mediaId = "";
        try {
            if (graphicType == 3) {
                TmCarKnowledges knowDto = tmSmartReplyMapper.queryCarKnowledgeById(graphicId);
                if (knowDto != null) {
                    fileUrl = knowDto.getListImage();
                } else {
                    throw new ServiceBizException("查询不到该用车知识");
                }
            } else {
                NewsActivityDto newsDto = tmSmartReplyMapper.queryInforById(graphicId);
                if (newsDto != null) {
                    if (newsDto.getTitleImage() != null) {
                        fileUrl = newsDto.getTitleImage();
                    } else {
                        // 测试地址
                        fileUrl = "http://wxtest.gmmc.com.cn/wx/fs01/forum/GMMC_log.jpg";
                        // 生产地址
                        // fileUrl = "http://i-club.gmmc.com.cn/fs01/forum/GMMC_log.jpg";
                    }
                } else {
                    throw new ServiceBizException("查询不到该资讯活动");
                }
            }
            String accessToken = tokenService.genAccessToken();

            String upLoadingUrl = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + accessToken
                                  + "&type=" + "image";

            logger.info("getMediaUpLoadingUrl-upLoadingUrl=" + upLoadingUrl);
            String resultBody = HttpsUtil.connectHttpsByPost(upLoadingUrl, null, fileUrl);

            logger.info("uploadMultiFile() response=" + resultBody);
            JSONObject resultJSON = JSONObject.fromObject(resultBody);

            if (resultJSON != null) {
                if (resultJSON.get("media_id") != null) {
                    logger.info("上传图片永久素材成功");
                    mediaId = resultJSON.get("media_id").toString();
                } else {
                    logger.info("上传图片永久素材失败");
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return mediaId;
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public Map<String, Object> insertSubMenuChild(List<WechatSmartReplyDto> listDto) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            tmSmartReplyMapper.insertSubmenuReply(listDto);
            resultMap.put("errorCode", 0);
            resultMap.put("errorMsg", "插入成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultMap.put("errorCode", 1);
            resultMap.put("errorMsg", "插入失败");
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultMap;
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public Map<String, Object> updatekeyWordReply(List<WechatSmartReplyDto> replyDto,
                                                  List<WechatKeyWordDto> keywordDto) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            tmSmartReplyMapper.updatekeyWord(keywordDto);
            if (replyDto.get(0).getReplyType() == 2) {
                String replyContent = getPicTextMediaId(replyDto.get(0).getGraphicId(),
                                                        replyDto.get(0).getGraphicType());
                if (null != replyContent && "" != replyContent) {
                    replyDto.get(0).setReplyContent(replyContent);
                } else {
                    resultMap.put("errorWeChat", "1");
                    resultMap.put("errorWeChatMsg", "微信上传图文失败");
                    throw new ServiceBizException("微信上传图文失败");
                }
            }
            tmSmartReplyMapper.updateReplky(replyDto);
            resultMap.put("errorCode", 0);
            resultMap.put("errorMsg", "更新成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultMap.put("errorCode", 1);
            resultMap.put("errorMsg", "更新失败");
            throw new ServiceBizException(e.getMessage(), e);
        }
        return resultMap;
    }

    public Map<String, Object> queryNewsPublicer() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            List<Map<String, Object>> m = tmSmartReplyMapper.queryNewsPublisher();
            resultMap.put("dataMap", m);
            resultMap.put("errorCode", 0);
            resultMap.put("errorMsg", "查询成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultMap.put("errorCode", 1);
            resultMap.put("errorMsg", "查询失败");
        }
        return resultMap;
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public Map<String, Object> deleteReply(Integer replyId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            tmSmartReplyMapper.deleteReply(replyId);
            resultMap.put("errorCode", 0);
            resultMap.put("errorMsg", "删除成功");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultMap.put("errorCode", 1);
            resultMap.put("errorMsg", "删除失败");
        }
        return resultMap;
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public Map<String, Object> alterReply(AlterReplyDto alterReplyDto) throws ServiceBizException, ServiceBizException {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        int rootId = -1;
        try {
            if (alterReplyDto.getReplyId() != null) {
                logger.info("存在ReplyID，先将数据库中原先的数据删除");
                int a = tmSmartReplyMapper.deleteKeywordByRID(alterReplyDto.getReplyId());
                logger.info("关键字表中删除了" + a + "条数据");
                int b = tmSmartReplyMapper.deleteReply(alterReplyDto.getReplyId());
                logger.info("回复表中删除了" + b + "条数据");
                List<WechatKeyWordDto> keyList = alterReplyDto.getKeyWordReply().getKeywordDto();
                logger.info("关键字List长度为：" + keyList.size());
                List<WechatSmartReplyDto> replyList = alterReplyDto.getKeyWordReply().getReplyDto();
                logger.info("回复List长度为：" + replyList.size());
                List<Map<String, Object>> menuList = alterReplyDto.getMenuList();
                logger.info("菜单List长度为：" + menuList.size());
                if (menuList.size() == 0) {
                    logger.info("回复内容没有菜单");
                    if (replyList.get(0).getReplyType() == 2) {
                        String replyContent = getPicTextMediaId(replyList.get(0).getGraphicId(),
                                                                replyList.get(0).getGraphicType());
                        if (null != replyContent && "" != replyContent) {
                            replyList.get(0).setReplyContent(replyContent);
                        } else {
                            resultMap.put("errorWeChat", "1");
                            resultMap.put("errorWeChatMsg", "微信上传图文失败");
                            throw new ServiceBizException("微信上传图文失败");
                        }
                    }
                    Integer id = tmSmartReplyMapper.selectReplyId();
                    replyList.get(0).setId(id);
                    replyList.get(0).setSubmenuParentId(id);
                    int c = tmSmartReplyMapper.insertSingleReply(replyList.get(0));
                    logger.info("回复表中插入了" + c + "条数据");
                    rootId = replyList.get(0).getId();
                } else {
                    logger.info("回复内容有菜单");
                    // for (int i = 0; i < menuList.size(); i++) {
                    rootId = traverseInsertMenuMap(menuList);
                    // }
                }
                tmSmartReplyMapper.updateStatus(rootId, alterReplyDto.getStatus());
                for (WechatKeyWordDto wechatKeyWordDto : keyList) {
                    wechatKeyWordDto.setReplyId(rootId);
                }
                int e = tmSmartReplyMapper.insertKeywordAndRID(keyList);
                logger.info("关键字表中插入了" + e + "条数据");
                resultMap.put("errorCode", 0);
                resultMap.put("errorMsg", "修改成功");
            } else {
                logger.info("没有ReplyID，不可修改");
                resultMap.put("errorCode", 1);
                resultMap.put("errorMsg", "修改失败");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultMap.put("errorCode", 1);
            resultMap.put("errorMsg", "修改失败");
        }
        return resultMap;
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public Map<String, Object> alterReplys(AlterReplyDto alterReplyDto) throws ServiceBizException,
                                                                        ServiceBizException {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (null != alterReplyDto.getReplyId()) {
                int rootId = -1;
                tmSmartReplyMapper.deleteKeywordByRID(alterReplyDto.getReplyId());
                tmSmartReplyMapper.deleteReply(alterReplyDto.getReplyId());
                List<WechatKeyWordDto> keyList = alterReplyDto.getKeyWordReply().getKeywordDto();
                List<WechatSmartReplyDto> replyList = alterReplyDto.getKeyWordReply().getReplyDto();
                List<Map<String, Object>> menuList = alterReplyDto.getMenuList();
                if (menuList.size() > 0 && !menuList.get(0).isEmpty()) {
                    for (int i = 0; i < menuList.size(); i++) {
                        rootId = traverseInsertMenuMap(menuList);
                    }
                } else if (replyList.size() > 0) {
                    if (replyList.get(0).getReplyType() == 2) {
                        String replyContent = getPicTextMediaId(replyList.get(0).getGraphicId(),
                                                                replyList.get(0).getGraphicType());
                        if (null != replyContent && "" != replyContent) {
                            replyList.get(0).setReplyContent(replyContent);
                        } else {
                            resultMap.put("errorWeChat", "1");
                            resultMap.put("errorWeChatMsg", "微信上传图文失败");
                            throw new ServiceBizException("微信上传图文失败");
                        }
                    }
                    Integer id = tmSmartReplyMapper.selectReplyId();
                    replyList.get(0).setId(id);
                    tmSmartReplyMapper.insertSingleReply(replyList.get(0));
                    rootId = replyList.get(0).getReplyId();
                }
                tmSmartReplyMapper.updateStatus(rootId, alterReplyDto.getStatus());
                for (WechatKeyWordDto wechatKeyWordDto : keyList) {
                    wechatKeyWordDto.setReplyId(rootId);
                }
                tmSmartReplyMapper.insertKeywordAndRID(keyList);
                resultMap.put("errorCode", 0);
                resultMap.put("errorMsg", "修改成功");
            } else {
                resultMap.put("errorCode", 1);
                resultMap.put("errorMsg", "修改失败");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            resultMap.put("errorCode", 1);
            resultMap.put("errorMsg", "修改失败");
        }
        return resultMap;
    }

    @Transactional(rollbackFor = ServiceBizException.class)
    public int traverseInsertMenuMap(List<Map<String, Object>> list) throws Exception {
        int rootId = -1;
        for (Map<String, Object> menu : list) {
            if (null != menu.get("replyObj")) {
                Integer id = tmSmartReplyMapper.selectReplyId();
                WechatSmartReplyDto wechatSmartReplyDto = new WechatSmartReplyDto();
                // Object obj = wechatSmartReplyDto.getClass().newInstance();
                Map<String, Object> replyMap = (Map<String, Object>) menu.get("replyObj");
                // BeanUtils.populate(obj, replyMap);
                // 2017-09-26 代码扫描
                logger.info("Map：" + replyMap);

                String replyContents = "";
                if (!CheckUtil.NullOrEmpty(replyMap.get("replyContent"))) {
                    replyContents = replyMap.get("replyContent").toString();
                }
                String replyType = "";
                if (!CheckUtil.NullOrEmpty(replyMap.get("replyType"))) {
                    replyType = replyMap.get("replyType").toString();
                }
                String status = "";
                if (!CheckUtil.NullOrEmpty(replyMap.get("status"))) {
                    status = replyMap.get("status").toString();
                }
                String submenuParentId = "";
                if (!CheckUtil.NullOrEmpty(replyMap.get("submenuParentId"))) {
                    submenuParentId = replyMap.get("submenuParentId").toString();
                }
                String submenuSequenceId = "";
                if (!CheckUtil.NullOrEmpty(replyMap.get("submenuSequenceId"))) {
                    submenuSequenceId = replyMap.get("submenuSequenceId").toString();
                }
                String menuInfo = "";
                if (!CheckUtil.NullOrEmpty(replyMap.get("menuInfo"))) {
                    menuInfo = replyMap.get("menuInfo").toString();
                }
                String graphicId = "";
                if (!CheckUtil.NullOrEmpty(replyMap.get("graphicId"))) {
                    graphicId = replyMap.get("graphicId").toString();
                }
                String graphicType = "";
                if (!CheckUtil.NullOrEmpty(replyMap.get("graphicType"))) {
                    graphicType = replyMap.get("graphicType").toString();
                }

                if (replyContents != null && replyContents != "") {
                    wechatSmartReplyDto.setReplyContent(replyContents);
                }
                if (replyType != null && replyType != "") {
                    wechatSmartReplyDto.setReplyType(Integer.valueOf(replyType));
                }
                if (status != null && status != "") {
                    wechatSmartReplyDto.setStatus(Integer.valueOf(status));
                }
                if (submenuParentId != null && submenuParentId != "") {
                    wechatSmartReplyDto.setSubmenuParentId(Integer.valueOf(submenuParentId));
                }
                if (submenuSequenceId != null && submenuSequenceId != "") {
                    wechatSmartReplyDto.setSubmenuSequenceId(Integer.valueOf(submenuSequenceId));
                }
                if (menuInfo != null && menuInfo != "") {
                    wechatSmartReplyDto.setMenuInfo(menuInfo);
                }
                if (graphicId != null && graphicId != "") {
                    wechatSmartReplyDto.setGraphicId(Integer.valueOf(graphicId));
                }
                if (graphicType != null && graphicType != "") {
                    wechatSmartReplyDto.setGraphicType(Integer.valueOf(graphicType));
                }

                Integer parentId = null;
                if (menu.get("submenuParentId") != null) {
                    parentId = Integer.valueOf(menu.get("submenuParentId").toString());
                    logger.info("获取到的父级ID为：" + parentId);
                    (wechatSmartReplyDto).setSubmenuParentId(parentId);
                }
                if (wechatSmartReplyDto.getReplyType() == 2) {
                    logger.info("处理图文回复");
                    String replyContent = getPicTextMediaId(wechatSmartReplyDto.getGraphicId(),
                                                            wechatSmartReplyDto.getGraphicType());
                    if (null != replyContent && "" != replyContent) {
                        wechatSmartReplyDto.setReplyContent(replyContent);
                    } else {
                        throw new ServiceBizException("微信上传图文失败");
                    }
                }
                wechatSmartReplyDto.setId(id);
                logger.info("ID为：>>>>>>>" + wechatSmartReplyDto.getId());
                tmSmartReplyMapper.insertSingleReply(wechatSmartReplyDto);
                rootId = id;// ((WechatSmartReplyDto) obj).getReplyId();
                if (null != menu.get("child")) {
                    List<Map<String, Object>> childList = (List<Map<String, Object>>) menu.get("child");
                    if (childList.size() != 0) {
                        logger.info("存在子集");
                        for (int i = 0; i < childList.size(); i++) {
                            childList.get(i).put("submenuParentId", id);
                        }
                        traverseInsertMenuMap(childList);
                    }
                }
            }
        }
        return rootId;
    }

    public Map<String, Object> test() throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            WechatSmartReplyDto wechatSmartReplyDto = new WechatSmartReplyDto();
            wechatSmartReplyDto.setId(11);
            wechatSmartReplyDto.setReplyType(1);
            wechatSmartReplyDto.setReplyContent("啊哈哈哈");
            wechatSmartReplyDto.setGraphicType(null);
            wechatSmartReplyDto.setGraphicId(null);
            wechatSmartReplyDto.setSubmenuParentId(null);
            wechatSmartReplyDto.setSubmenuSequenceId(null);
            wechatSmartReplyDto.setStatus(1);
            wechatSmartReplyDto.setMenuInfo(null);
            int a = tmSmartReplyMapper.insertSingleReply(wechatSmartReplyDto);
            logger.info("插入" + a + "条");
            int s = a / 0;
            logger.info("end");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException("微信上传图文失败");
        }
        return result;
    }

    public PageInfo<TtUserProblem> queryCount(String pageSize, Integer pageNum, String content) throws Exception {
        List<TtUserProblem> list = new ArrayList<TtUserProblem>();
        try {
            Page<TtUserProblem> ss = PageHelper.startPage(pageNum, Integer.parseInt(pageSize));
            list = ttUserProblemMapper.queryCount(content);
            logger.info("查询结果条数为：" + list.size());
            PageInfo<TtUserProblem> page = new PageInfo<>(list);
            return page;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceBizException("查询异常");
        }
    }
}
